﻿#include "mass.h"
#include "ui_mass.h"

Mass::Mass(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Mass)
{
    ui->setupUi(this);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
}

Mass::~Mass()
{
    delete ui;
}

void Mass::updateView()
{
    model->setTable(TB_MASS);
    model->setFilter(QString("date = '%1'").arg(Env::date));
    model->select();

    model->setHeaderData(0,Qt::Horizontal,QStringLiteral("ID"));
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("单号"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("质量"));
}

void Mass::on_btn_submit_clicked()
{
    num=ui->in_num->text();
    mass=ui->in_mass->text();
    if(num.isEmpty() || mass.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("单号、质量不能为空！"),QMessageBox::Ok);
    }
    else
    {
        if(saveRecord())
        {
            updateView();
            ui->in_num->clear();
            ui->in_mass->clear();
            ui->lbl_status->setText(QStringLiteral("记录已提交"));
        }
        else
            ui->lbl_status->setText(QStringLiteral("提交失败！数据库异常"));
    }
}

bool Mass::saveRecord()
{
    QSqlQuery query;
    query.prepare("insert into td_mass (date,number,mass) values (?,?,?)");
    query.addBindValue(Env::date);
    query.addBindValue(num);
    query.addBindValue(mass);
    return query.exec();
}

void Mass::on_btn_save_clicked()
{
    model->submitAll();
}
